package me.muci.A_base.nodeFlow;

import org.junit.Test;

import java.io.*;

/**
 * ClassName: FileInputOutputStream <br/>
 * Description: <br/>
 * date: 2021/8/11 18:01<br/>
 *
 * @author muci<br />
 * @description
 * @since JDK 1.8
 */
public class FileInputOutputStreamTest {
    /**
     * 对于文本文件(.txt,java,c,.cpp)文件使用字符流处理
     * 对于非文本文件(媒体资源文件)，使用字节流处理
     */
    @Test
    public void inputStream() {
        File file = new File("src\\main\\resources\\input.txt");

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);

            byte[] bytes = new byte[5];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                String s = new String(bytes, 0, len);
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 图片复制
     */
    @Test
    public void copyImage() {
        File inputImage = new File("src\\main\\resources\\image.jpg");
        File outImage = new File("src\\main\\resources\\image_copy.jpg");

        try (
                FileInputStream fileInputStream = new FileInputStream(inputImage);
                FileOutputStream fileOutputStream = new FileOutputStream(outImage)
        ) {
            byte[] bytes = new byte[5];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 指定路径下的文件复制
     */
    public void copyByFilePath(String sourceFilePath, String targetFilePath){
        File sourceFile = new File(sourceFilePath);
        File targetFile= new File(targetFilePath);

        try (
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                FileOutputStream fileOutputStream = new FileOutputStream(targetFile)
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test(){
        long l = System.currentTimeMillis();
        System.out.println("拷贝开始,开始时间: " + l);
        this.copyByFilePath("src\\main\\resources\\video.mp4","src\\main\\resources\\video_copy.mp4");
        long l1 = System.currentTimeMillis();
        System.out.println("拷贝结束，结束时间： " + l1);
        System.out.println(l1 - l);
        //8631方法
    }
}
